/*
 * @Author: zhangyujie
 * @Date:   2015-08-12 10:45:35
 * @Last Modified by:   zhangyujie
 * @Last Modified time: 2015-08-14 16:18:53
 */

'use strict';

(function() {

	var Y = window.Y || {}

	var util = {

		getNumByRate: function(w, rate) {

			if (typeof rate === 'string' && rate.indexOf('%')) {

				return w * Number(rate.replace('%', '')) / 100
			} else if (typeof rate === 'string' && rate.indexOf('px')) {

				return Number(rate.replace('px', ''))
			} else {

				return Number(rate)
			}
		},
		getTextSize: function(text, style) {

			var span, position, width, height

			span = document.createElement('span')

			span.innerText = text

			for (var key in style) {

				span.style[key] = style[key]
			}

			document.body.appendChild(span)

			position = span.getBoundingClientRect()

			width = position.width

			height = position.height

			document.body.removeChild(span)

			return {

				width: width,
				height: height
			}
		}
	}

	Y.six = function(setting) {

		var selector = setting.selector,
			series = setting.series,
			otherColor = setting.otherColor,
			legendSetting = setting.legend,
			colorset = setting.colorset,
			margin = setting.margin,
			width = document.querySelector(selector).offsetWidth,
			height = document.querySelector(selector).offsetHeight,
			length = series.length,
			dom = document.querySelector(selector),
			contentW = width - margin.left - margin.right,
			contentH = height - margin.top - margin.bottom

		var svg,
			content,
			totalGroup,
			xScale,
			yScale,
			incomeGroup,
			circle,
			legend,
			titleGroup,
			totalGroup,
			xAxis,
			yAxis,
			xAxisData = setting.xAxis,
			yAxisData = [],
			yMax,
			diff

		yMax = d3.max(series[2]['data'], function(d) {
			return d
		})

		diff = yMax / 4
		for (var i = 0; i < yMax; i += diff) {
			yAxisData.push(Number(i.toFixed(0)))
		}
		yAxisData.push(yMax)
		xScale = d3.scale.ordinal()
			.domain(xAxisData)
			// .rangeRoundPoints([margin.left, width - margin.right])
			.rangeRoundPoints([0, contentW])
		yScale = d3.scale.linear()
			.domain([0, yMax])
			//.range([height - margin.bottom, margin.top])
			.range([contentH, 0])

		svg = d3.select(selector).append('svg')
			.attr('width', width)
			.attr('height', height)

		legend = svg.append('g')
			.attr('class', 'legend')


		titleGroup = legend.append('g')
			.attr('class', 'title')
			.attr('transform', 'translate(' + legendSetting['title']['margin']['left'] + ',' + legendSetting['title']['margin']['top'] + ')')
		totalGroup = legend.append('g')
			.attr('class', 'total')
			.attr('transform', 'translate(' + legendSetting['total']['margin']['left'] + ',' + legendSetting['total']['margin']['top'] + ')')

		for (var j = 0; j < length; j += 1) {
			titleGroup.append('circle')
				.attr('transform', 'translate(' + (j * legendSetting['title']['offset']['left']) + ',' + legendSetting['title']['offset']['top'] + ')')
				.attr('r', legendSetting['title']['circle']['r'])
				.attr('cx', legendSetting['title']['circle']['cx'])
				.attr('cy', legendSetting['title']['circle']['cy'])
				.attr('fill', series[j]['color'])
			titleGroup.append('text')
				.text(series[j]['name'])
				.attr('x', legendSetting['title']['text']['x'])
				.attr('y', legendSetting['title']['text']['y'])
				.attr('transform', 'translate(' + (j * legendSetting['title']['offset']['left']) + ',' + legendSetting['title']['offset']['top'] + ')')
				.style(legendSetting['title']['text']['textStyle'])

			totalGroup.append('circle')
				.attr('transform', 'translate(' + (j * legendSetting['total']['offset']['left']) + ',' + legendSetting['total']['offset']['top'] + ')')
				.attr('r', legendSetting['total']['circle']['r'])
				.attr('cx', legendSetting['total']['circle']['cx'])
				.attr('cy', legendSetting['total']['circle']['cy'])
				.attr('fill', series[j]['color'])

			totalGroup.append('text')
				.text(function() {
					var text = j == length - 1 ? d3.sum(series[j]['data']) + '万' : d3.sum(series[j]['data'])
					return text
				})
				.attr('x', legendSetting['total']['text']['x'])
				.attr('y', legendSetting['total']['text']['y'])
				.attr('transform', 'translate(' + (j * legendSetting['total']['offset']['left']) + ',' + legendSetting['total']['offset']['top'] + ')')
				.style(legendSetting['total']['text']['textStyle'])

		}

		content = svg.append('g')
			.attr('class', 'content')
			.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

		xAxis = d3.svg.axis()
			.scale(xScale)
			.tickValues(xAxisData)
			.tickPadding(10)
			.orient('bottom')
			.tickSize(0)
		yAxis = d3.svg.axis()
			.scale(yScale)
			.tickValues(yAxisData)
			.tickPadding(10)
			.orient('left')
			.tickSize(0)

		content.append('g')
			.attr('class', 'xAxis')
			.attr('transform', 'translate(' + 0 + ',' + (contentH) + ')')
			.call(xAxis)

		content.append('g')
			.attr('class', 'yAxis')
			.attr('transform', 'translate(' + 0 + ',' + 0 + ')')
			.call(yAxis)

		svg.selectAll('.yAxis .tick')
			.attr('opacity', function(d, i) {

				d3.select(this).append('line')
					.attr('x1', 0)
					.attr('y1', 0)
					.attr('x2', (contentW))
					.attr('y2', 0)

			})


		var area = d3.svg.area()
			.x(function(d, i) {
				return xScale(xAxisData[i])
			})
			.y0(contentH)
			.y1(function(d, i) {
				return yScale(d)
			});

		var valueline = d3.svg.line()
			.interpolate("linear")
			.x(function(d, i) {
				return xScale(xAxisData[i])
			})
			.y(function(d, i) {

				return yScale(d)
			})

		var brokeArea = content.append('g')
			.attr('class', 'brokeArea')



		for (var j = length - 1; j >= 0; j -= 1) {

			var brokeLinear = content.append('defs')
				.append('linearGradient')
				.attr('id', 'brokeArea' + j)
				.attr('x1', '100%')
				.attr('y1', '100%')
				.attr('x2', '100%')
				.attr('y2', '0%')

			brokeLinear.append('stop')
				.attr('offset', '0%')
				.style({
					'stop-color': '#DDEDFD',
					'stop-opacity': 0.5
				})

			brokeLinear.append('stop')
				.attr('offset', '100%')
				.style({
					'stop-color': series[j]['color'],
					'stop-opacity': 1
				})

			var pct = svg.select(".brokeArea")
				.append("g")
				.attr("class", "pct");
			pct.append("path")
				.datum(series[j]['data'])
				.attr("d", area)
				.style("fill", 'url(#brokeArea' + j + ')')

			brokeArea.append("path")
				.attr('class', 'line' + j)
				.attr('fill', 'none')
				.attr("stroke", series[j]['color'])
				.attr("stroke-width", 2)
				.attr("d", valueline(series[j]['data']))

			brokeArea.selectAll('.circle' + j)
				.data(series[j]['data'])
				.enter()
				.append('circle')
				.attr('class', '.circle' + j)
				.attr('r', setting.radius)
				.attr('cx', function(d, i) {
					return xScale(xAxisData[i])
				})
				.attr('cy', function(d, i) {
					return yScale(d)
				})
				.attr('fill', '#fff')
				.attr('stroke', '#84C6FF')
				.attr('stroke-width', 1)

		}

		var lineWrap = content.append('g')
			.style('display', 'none')
		var line = lineWrap
			.append('line')
			.attr('x1', 0)
			.attr('y2', 0)
			.attr('x2', 0)
			.attr('y2', height - margin.top - margin.bottom)
			.attr('fill', '#ffc10e')
			.attr('stroke', setting.series[0].color)
		var circleWrap = lineWrap.selectAll('.circle')
			.data([1, 2, 3])
			.enter()
			.append('g')

		circleWrap.append('circle')
			.attr('r', 8)
			.attr('fill', '#fff')
			.attr('stroke-width', '2px')
			.attr('stroke', function(d, i) {

				return setting.series[i].color
			})

		circleWrap.append('circle')
			.attr('r', 4)
			.attr('fill', function(d, i) {

				return setting.series[i].color
			})
		content
			.on('touchstart', touch)
			.on('touchmove', touch)

		function touch() {

			var target = null,
				tagName, height,
				position, left, key,
				lineValue, rectValue,
				index, arr

			position = d3.mouse(dom)
			target = d3.event.target
			tagName = target.tagName

			left = position[0] - margin.left


			if (left >= 0 && left <= contentW) {

				arr = getData(left, 0)

				lineWrap.style('display', 'block')

				line
					.attr('transform', 'translate(' + left + ',' + 0 + ')')

				circleWrap.attr('transform', function(d, i) {

					return 'translate(' + left + ',' + getData(left, i)[1] + ')'
				})
			}

		}

		function getData(num, index) {

			var xScaleData = setting.xAxis
			var unitData = contentW / (xScaleData.length - 1),
				preIndex,
				nextIndex, currentIndex, k,
				vaildIndex, y, currentValue, vaildValue, x, b,
				data = setting.series[index].data



			var currentIndex = Math.floor(num / unitData)

			if (currentIndex < 0) {

				currentIndex = 0
			}

			if (currentIndex > xScaleData.length - 1) {

				currentIndex = xScaleData.length - 1
			}

			vaildIndex = currentIndex + 1

			currentValue = yScale(data[currentIndex])

			vaildValue = yScale(data[vaildIndex])

			x = num - (currentIndex * unitData)

			k = 1

			b = currentValue

			y = k * (vaildValue - currentValue) * x / unitData + b

			return [currentIndex, y]
		}

	}

	window.Y = Y
}())